local tongliao = fk.CreateSkill {

  name = "joy__tongliao",

  tags = {  },

}



tongliao:addEffect(fk.EventPhaseEnd, {
  name = "joy__tongliao",
  anim_type = "special",
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(tongliao.name) and player.phase == player.Draw and not player:isKongcheng()
  end,
  on_cost = function(self, event, target, player, data)
    local room = player.room
    local ids = table.filter(player.player_cards[Player.Hand], function(id)
      return table.every(player.player_cards[Player.Hand], function(id2)
        return Fk:getCardById(id).number <= Fk:getCardById(id2).number end) end)
    local cards = room:askForCard(player, 1, 1, false, tongliao.name, true, ".|.|.|.|.|.|"..table.concat(ids, ","), "#joy__tongliao-invoke")
    if #cards > 0 then
      event:setCostData(self, cards[1])
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local id = event:getCostData(self)
    local mark = type(player:getMark("joy__tongliao")) == "table" and player:getMark("joy__tongliao") or {}
    table.insertIfNeed(mark, id)
    room:setPlayerMark(player, "joy__tongliao", mark)
    room:setCardMark(Fk:getCardById(id), "@@joy__tongliao-inhand", 1)
  end,
})

tongliao:addEffect(fk.AfterCardsMove, {
  name = "#joy__tongliao_delay",
  mute = true,
  events = {fk.AfterCardsMove},
  can_trigger = function(self, event, target, player, data)
    if player.dead or type(player:getMark("joy__tongliao")) ~= "table" then return false end
    local mark = player:getMark("joy__tongliao")
    for _, move in ipairs(data) do
      if move.from==player then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand and table.contains(mark, info.cardId) then
            return true
          end
        end
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player, "joy__tongliao", "drawcard")
    player:broadcastSkillInvoke("joy__tongliao")
    local mark = player:getMark("joy__tongliao")
    local x = 0
    for _, move in ipairs(data) do
      if move.from==player then
        for _, info in ipairs(move.moveInfo) do
          if info.fromArea == Card.PlayerHand and table.removeOne(mark, info.cardId) then
            x = x + Fk:getCardById(info.cardId).number
          end
        end
      end
    end
    room:setPlayerMark(player, "joy__tongliao", #mark > 0 and mark or 0)
    if x > 0 then
      room:drawCards(player, x, "joy__tongliao")
    end
  end,
})

return tongliao